package com.framework.projectframework.plugin.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤请求中前后空格字符
 */
@Slf4j
@Component
public class SpaceFilter extends HttpFilter {

    @Override
    public void init() throws ServletException {
        log.info("-------------------- 字符过滤器启动 --------------------");
    }

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        chain.doFilter(new SpaceHttpServletRequestWrapper(request), response);
    }

    @Override
    public void destroy() {
        log.info("-------------------- 字符过滤器停止 --------------------");
    }

    class SpaceHttpServletRequestWrapper extends HttpServletRequestWrapper {

        public SpaceHttpServletRequestWrapper(HttpServletRequest request) {
            super(request);
        }

        @Override
        public String[] getParameterValues(String parameter) {
            String[] values = super.getParameterValues(parameter);
            if (values == null) {
                return new String[0];
            }
            int count = values.length;
            String[] encodedValues = new String[count];
            for (int i = 0; i < count; i++) {
                encodedValues[i] = values[i].trim();
            }
            return encodedValues;
        }

        @Override
        public String getParameter(String parameter) {
            String value = super.getParameter(parameter);
            if (value == null) {
                return null;
            }
            return value.trim();
        }

    }

}

